﻿// ***********************************************************************
// Assembly         : MVC4Portal
// Author           : LJO+01 (Laurent Jordi)
// Created          : 06-05-2013
// Last Modified By : LJO+01 (Laurent Jordi)
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="DynaStructureController.cs" company="Copyright © Innovacall 2011">
//     Copyright (c) Copyright © Innovacall 2011. All rights reserved.
// </copyright>
// <summary>
// this controller is not a web api because we use RederPartialViewToString
// </summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using EmitMapper;
using InnovaApp.Layers.CommonLayer.Controllers;
using InnovaApp.Layers.CommonLayer.Controllers.ViewControllers.LayoutViewControllers;
using InnovaApp.Layers.DataLayer;
using InnovaApp.Layers.DomainLayer;
using InnovaApp.Layers.ResourcesLayer.Properties;
using InnovaApp.Portals.MVC4Portal.Controllers.ViewControllers.LayoutViewControllers.DynaContents;
using InnovaApp.Portals.MVC4Portal.Models;
using InnovaApp.Portals.MVC4Portal.Models.JSonModels;
using InnovaApp.Portals.MVC4Portal.Models.MetaModels;
using INNOVACALL.Framework.Common.Controllers.ViewControllers;
using INNOVACALL.Framework.Common.Extensions;
using INNOVACALL.Framework.Common.InnovacallExceptions;
using INNOVACALL.Framework.Common.Logging;
using INNOVACALL.Framework.Common.Models.ViewModels.MetaModels;
using INNOVACALL.Framework.Common.Models.ViewModels.MetaModels.LayoutMenus;
using INNOVACALL.Framework.Common.Models;

namespace InnovaApp.Portals.MVC4Portal.Controllers.ViewControllers.LayoutViewControllers
{
    /// <summary>
    /// Class DynaStructureController
    /// </summary>
    public class DynaStructureController : INNOVACALL.Framework.Common.Controllers.ViewControllers._ViewControllers_Base
    {
        /// <summary>
        /// Initializes data that might not be available when the constructor is called.
        /// </summary>
        /// <param name="requestContext">The HTTP context and route data.</param>
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.eMethodBase = "InnovaApp.Portals.InnovaAppFrontOfficePortal.Controllers.DynaStructureController";
            base.Initialize(requestContext);
        }

        /// <summary>
        /// Feed LayoutMenu when Add or Edit
        /// </summary>
        /// <param name="language">The language.</param>
        /// <param name="jSonModel">The ajax model.</param>
        /// <returns>JsonResult.</returns>
        /// <exception cref="INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException">
        /// </exception>
        /// <exception cref="INNOVACALL.Framework.Common.InnovacallExceptions.InnovaTreeException">Not found</exception>
        public JsonResult LayoutMenuItemFeed(string language, LayoutMenuItemFeed_JSonModel jSonModel)
        {
            JsonResult toReturn = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            string eMethod = eMethodBase + "LayoutMenuItemAddSubItem[POST]";
            object eParameters = new { ajaxModel = jSonModel };
            LayoutMenu_MetaModel MenuToReturn = null;
            LayoutMenu dbLayoutMenu = null;
            LayoutMenu dbParentLayoutMenu;
            LayoutMenu_Translation_MetaModel layoutMenu_Translation_MetaModelToAdd = null;
            Structure_Page dbStructure_Page = null;
            LayoutMenu_Translation dbLayoutMenu_Translation = null;
            List<Language_MetaModel> Languages = PortalEnvironment.Languages.Split(',').Select(x => new Language_MetaModel(x)).ToList();
            INNOVACALL.Framework.Common.MVCHelpers.Localization.CommonLocalization.SetCurrentThreadLanguage(language);
            int languageIndex = 0;
            string ancestors = string.Empty;
            string pageNamePart = string.Empty;
            bool isAHomePage = false;
            string htmlContent = string.Empty;
            string scriptToExecute = string.Empty;
            string messageTitle = string.Empty;
            string message = string.Empty;
            string contentLanguage = GetContentLanguage(jSonModel.DirectURL);

            using (DataRepositories _dataContext = new DataRepositories())
            {
                try
                {
                    if (jSonModel.LayoutMenu_Translation_Id == -1)
                    {
                        MenuToReturn = new LayoutMenu_MetaModel();
                        MenuToReturn.FK_LayoutMenu = jSonModel.LayoutMenuTranslationLayoutMenuParent;
                        foreach (Language_MetaModel language_MetaModel in Languages)
                        {
                            ancestors = string.Empty;
                            Language dbLanguage = _dataContext.Language_Rep.Query(x => x.Description == language_MetaModel.Language).FirstOrDefault();
                            if (dbLanguage == null)
                            {
                                throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, string.Format(Resources.ErrMsg_LayoutMenuItemFeed_UnknownLanguage, language_MetaModel.Language));
                            }
                            layoutMenu_Translation_MetaModelToAdd = new LayoutMenu_Translation_MetaModel();
                            layoutMenu_Translation_MetaModelToAdd.Active = false;
                            layoutMenu_Translation_MetaModelToAdd.ButtonCaption = string.Empty;
                            layoutMenu_Translation_MetaModelToAdd.ButtonToolTip = string.Empty;
                            layoutMenu_Translation_MetaModelToAdd.CssClass = string.Empty;
                            layoutMenu_Translation_MetaModelToAdd.DirectURL = string.Empty;
                            layoutMenu_Translation_MetaModelToAdd.FK_Language = dbLanguage.Id;
                            layoutMenu_Translation_MetaModelToAdd.FK_LayoutMenu = -1;
                            layoutMenu_Translation_MetaModelToAdd.Language = language_MetaModel;
                            layoutMenu_Translation_MetaModelToAdd.LanguageIndex = languageIndex;
                            if (jSonModel.LayoutMenuTranslationLayoutMenuParent == null) //Menu bar
                            {
                                layoutMenu_Translation_MetaModelToAdd.LevelCount = _dataContext.LayoutMenu_Rep.Query(x => x.FK_LayoutMenu == null).Count();
                                ancestors = string.Empty;
                            }
                            else
                            {
                                layoutMenu_Translation_MetaModelToAdd.LevelCount = _dataContext.LayoutMenu_Rep.Query(x => x.Id == jSonModel.LayoutMenuTranslationLayoutMenuParent).First().LayoutMenu1.Count;
                                dbParentLayoutMenu = _dataContext.LayoutMenu_Rep.Query(x => x.Id == jSonModel.LayoutMenuTranslationLayoutMenuParent).FirstOrDefault();
                                if (dbParentLayoutMenu == null)
                                {
                                    throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, string.Format(Resources.ErrMsg_LayoutMenuItemFeed_ParentLayoutMenuNull, jSonModel.LayoutMenuTranslationLayoutMenuParent));
                                }
                                LayoutViewControllersStaticTools.BuildAncestorsString(dbLanguage, dbParentLayoutMenu, ref ancestors);
                            }
                            layoutMenu_Translation_MetaModelToAdd.MenuNameURLFormatted = string.Empty;
                            layoutMenu_Translation_MetaModelToAdd.OriginalDirectURL = string.Empty;
                            layoutMenu_Translation_MetaModelToAdd.PageNameURLFormatted = string.Empty;
                            layoutMenu_Translation_MetaModelToAdd.PageTitle = string.Empty;
                            layoutMenu_Translation_MetaModelToAdd.Ancestors = ancestors;
                            MenuToReturn.Translations.Add(layoutMenu_Translation_MetaModelToAdd);
                            languageIndex++;
                        }
                    }
                    else
                    {
                        if (jSonModel.LayoutMenuTranslationLayoutMenuParent == null)
                        {
                            dbLayoutMenu_Translation = _dataContext.LayoutMenu_Translation_Rep.Query(x => x.Id == jSonModel.LayoutMenu_Translation_Id && x.LayoutMenu.FK_LayoutMenu == null).FirstOrDefault();
                        }
                        else
                        {
                            dbLayoutMenu_Translation = _dataContext.LayoutMenu_Translation_Rep.Query(x => x.Id == jSonModel.LayoutMenu_Translation_Id && x.LayoutMenu.FK_LayoutMenu == jSonModel.LayoutMenuTranslationLayoutMenuParent).FirstOrDefault();
                        }
                        dbLayoutMenu = dbLayoutMenu_Translation.LayoutMenu;
                        if (dbLayoutMenu == null)
                        {
                            throw new INNOVACALL.Framework.Common.InnovacallExceptions.InnovaTreeException(eMethod, eParameters, "Not found");
                        }
                        MenuToReturn = ObjectMapperManager.DefaultInstance.GetMapper<LayoutMenu, LayoutMenu_MetaModel>().Map(dbLayoutMenu);
                        languageIndex = 0;
                        foreach (Language_MetaModel language_MetaModel in Languages)
                        {
                            Language dbLanguage = _dataContext.Language_Rep.Query(x => x.Description == language_MetaModel.Language).FirstOrDefault();
                            if (dbLanguage == null)
                            {
                                throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, string.Format(Resources.ErrMsg_LayoutMenuItemFeed_UnknownLanguage, language_MetaModel.Language));
                            }
                            dbLayoutMenu_Translation = _dataContext.LayoutMenu_Translation_Rep.Query(x => x.FK_LayoutMenu == dbLayoutMenu.Id && x.FK_Language == dbLanguage.Id).FirstOrDefault();
                            if (dbLayoutMenu_Translation == null)
                            {
                                throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.ErrMsg_LayoutMenuItemFeed_TranslationNotFound);
                            }
                            layoutMenu_Translation_MetaModelToAdd = ObjectMapperManager.DefaultInstance.GetMapper<LayoutMenu_Translation, LayoutMenu_Translation_MetaModel>().Map(dbLayoutMenu_Translation);
                            dbStructure_Page = _dataContext.Structure_Page_Rep.Query(x => x.FK_LayoutMenu_Translation == dbLayoutMenu_Translation.Id).FirstOrDefault();
                            if (dbStructure_Page == null)
                            {
                                throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.View_DynaContent_MenuEdition_StructurePageNotFound);
                            }
                            dbLayoutMenu_Translation.Structure_Page.Where(x => x.SortIndex == 1).FirstOrDefault();
                            layoutMenu_Translation_MetaModelToAdd.PageTitle = dbStructure_Page.Title;
                            layoutMenu_Translation_MetaModelToAdd.Language = language_MetaModel;
                            layoutMenu_Translation_MetaModelToAdd.LanguageIndex = languageIndex;
                            layoutMenu_Translation_MetaModelToAdd.SortIndex = dbLayoutMenu.SortIndex;
                            layoutMenu_Translation_MetaModelToAdd.LayoutMenuTranslationLayoutMenuParent = dbLayoutMenu.FK_LayoutMenu;
                            if (dbLayoutMenu_Translation.LayoutMenu.FK_LayoutMenu == null)
                            {
                                layoutMenu_Translation_MetaModelToAdd.LevelCount = _dataContext.LayoutMenu_Rep.Query(x => x.FK_LayoutMenu == null).Count();
                            }
                            else
                            {
                                layoutMenu_Translation_MetaModelToAdd.LevelCount = dbLayoutMenu_Translation.LayoutMenu.LayoutMenu2.LayoutMenu1.Count;
                            }

                            LayoutViewControllersStaticTools.BuildAncestorsString(dbLayoutMenu_Translation, ref ancestors);//, dbLayoutMenu_Translation.Language);
                            layoutMenu_Translation_MetaModelToAdd.Ancestors = ancestors;
                            isAHomePage = LayoutViewControllersStaticTools.IsAHomePage(dbLayoutMenu);
                            layoutMenu_Translation_MetaModelToAdd.PageNameURLFormatted = LayoutViewControllersStaticTools.GetPageNameURLFormatted(isAHomePage, dbStructure_Page);
                            layoutMenu_Translation_MetaModelToAdd.OriginalDirectURL = dbStructure_Page.DirectURL;
                            layoutMenu_Translation_MetaModelToAdd.DirectURL = layoutMenu_Translation_MetaModelToAdd.OriginalDirectURL;
                            MenuToReturn.Translations.Add(layoutMenu_Translation_MetaModelToAdd);
                            languageIndex++;
                        }
                    }
                    if (dbLayoutMenu == null)
                    {
                        MenuToReturn.Controllers = LayoutViewControllersStaticTools.GetMenuControllers(string.Empty);
                        MenuToReturn.DefaultActions = LayoutViewControllersStaticTools.GetMenuControllerActions(string.Empty, "Index");
                    }
                    else
                    {
                        MenuToReturn.Controllers = LayoutViewControllersStaticTools.GetMenuControllers(dbLayoutMenu.Controller);
                        MenuToReturn.DefaultActions = LayoutViewControllersStaticTools.GetMenuControllerActions(dbLayoutMenu.Controller.Trim(), "Index");
                    }
                    MenuToReturn.ContentLanguage = contentLanguage;
                    htmlContent = base.RenderPartialViewToString("_LayoutMenu", MenuToReturn);

                    toReturn.Data = new INNOVACALLAjaxResponse(
                        success: true,
                        domElementToUpdate: jSonModel.HtmlElementToUpdate,
                        htmlContent: htmlContent,
                        scriptToExecute: scriptToExecute,
                        messageTitle: messageTitle,
                        message: message,
                        additionalData: null
                    );

                }
                catch (Exception ex)
                {
                    toReturn.Data = new INNOVACALLAjaxResponse(
                        success: false,
                        domElementToUpdate: null,
                        htmlContent: null,
                        scriptToExecute: "$.fn.jqDialogAlert(a.messageTitle ,a.message,'');",
                        messageTitle: Resources.View_All_DialogErrorTitle,
                        message: ex.LayoutException(),
                        additionalData: null
                    );

                }
            }
            return toReturn;
        }

        /// <summary>
        /// Layouts the menu item add edit.
        /// </summary>
        /// <param name="language">The language.</param>
        /// <param name="layoutMenu">The layout menu.</param>
        /// <returns>JsonResult.</returns>
        /// <exception cref="INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException">
        /// </exception>
        [HttpPost, Authorize(Roles = "Admin"), ValidateInput(false)]
        //public JsonResult LayoutMenuItemAddEdit(LayoutMenuAddEditReturnModel layoutMenus)
        public JsonResult LayoutMenuItemAddEdit(string language, LayoutMenu_MetaModel layoutMenu)
        {
            JsonResult toReturn = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            string eMethod = eMethodBase + "LayoutMenuItemAddEdit[POST]";
            object eParameters = new { layoutMenu = layoutMenu };
            string defaultLanguage = PortalEnvironment.DefaultLanguage;
            string contentLanguage = GetContentLanguage(layoutMenu.ContentLanguage);
            string newMenuBar = string.Empty;
            MembershipUser currentUser = Membership.GetUser();
            string applicationName = Membership.ApplicationName;
            LayoutMenu dbLayoutMenu_ToAddEdit = null;
            Language dbLanguage = null;
            using (DataRepositories _dataContext = new DataRepositories())
            {
                using (TransactionScope TS = new TransactionScope())
                {
                    try
                    {
                        if (layoutMenu.Id == -1)
                        {
                            dbLayoutMenu_ToAddEdit = new LayoutMenu();
                            LayoutMenu_Translation dbLayoutMenu_Translation_ToAddEdit = null;
                            dbLayoutMenu_ToAddEdit.FK_InnoApplication = _dataContext.InnoApplication_Rep.Query(x => x.Name == applicationName).First().Id;
                            dbLayoutMenu_ToAddEdit.FK_LayoutMenu = layoutMenu.FK_LayoutMenu;
                            dbLayoutMenu_ToAddEdit.Name = layoutMenu.Name;
                            dbLayoutMenu_ToAddEdit.SortIndex = NewSortIndex(_dataContext, dbLayoutMenu_ToAddEdit.FK_InnoApplication, layoutMenu.FK_LayoutMenu);
                            dbLayoutMenu_ToAddEdit.Controller = layoutMenu.Controller;
                            dbLayoutMenu_ToAddEdit.DefaultAction = layoutMenu.DefaultAction;
                            dbLayoutMenu_ToAddEdit.DisplayMenuToPublicIfPrivate = layoutMenu.DisplayMenuToPublicIfPrivate;
                            dbLayoutMenu_ToAddEdit.DisplayMenuBar = layoutMenu.DisplayMenuBar;
                            _dataContext.LayoutMenu_Rep.Add(dbLayoutMenu_ToAddEdit);
                            _dataContext.Save();
                            foreach (LayoutMenu_Translation_MetaModel layoutMenu_Translation in layoutMenu.Translations)
                            {
                                dbLanguage = _dataContext.Language_Rep.Query(x => x.Description == layoutMenu_Translation.Language.Language).FirstOrDefault();
                                if (dbLanguage == null)
                                {
                                    throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, string.Format(Resources.ErrMsg_LayoutMenuItemAdd_UnknownLanguage, layoutMenu_Translation.Language.Language));
                                }
                                dbLayoutMenu_Translation_ToAddEdit = new LayoutMenu_Translation();
                                dbLayoutMenu_Translation_ToAddEdit.FK_LayoutMenu = dbLayoutMenu_ToAddEdit.Id;
                                dbLayoutMenu_Translation_ToAddEdit.FK_Language = dbLanguage.Id;
                                dbLayoutMenu_Translation_ToAddEdit.Active = layoutMenu_Translation.Active;
                                dbLayoutMenu_Translation_ToAddEdit.ButtonCaption = layoutMenu_Translation.ButtonCaption;
                                dbLayoutMenu_Translation_ToAddEdit.ButtonToolTip = layoutMenu_Translation.ButtonToolTip;
                                dbLayoutMenu_Translation_ToAddEdit.CssClass = layoutMenu_Translation.CssClass;
                                dbLayoutMenu_Translation_ToAddEdit.MenuNameURLFormatted = layoutMenu_Translation.MenuNameURLFormatted;
                                _dataContext.LayoutMenu_Translation_Rep.Add(dbLayoutMenu_Translation_ToAddEdit);
                                _dataContext.Save();
                                //Structure_Page
                                Structure_Page dbStructure_Page = _DynaContents_Base.PrepareEmptyStructurePage(dbLayoutMenu_Translation_ToAddEdit.Id, layoutMenu_Translation.PageNameURLFormatted, layoutMenu_Translation.DirectURL, dbLanguage.Description, layoutMenu_Translation.PageTitle);
                                _dataContext.Structure_Page_Rep.Add(dbStructure_Page);
                                _dataContext.Save();
                                ManagedContent dbManagedContent = _DynaContents_Base.PrepareEmptyManagedContent(dbStructure_Page.Id, dbLanguage.Description, currentUser);
                                _dataContext.ManagedContent_Rep.Add(dbManagedContent);
                                _dataContext.Save();
                            }

                        }
                        else
                        {
                            dbLayoutMenu_ToAddEdit = _dataContext.LayoutMenu_Rep.GetById(layoutMenu.Id);
                            if (dbLayoutMenu_ToAddEdit.InnoApplication.Name != applicationName)
                            {
                                throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.ErrMsg_LayoutMenuItemEdit_PrementMenuIdDontMatchApplicationName);
                            }
                            dbLayoutMenu_ToAddEdit.Name = layoutMenu.Name;
                            dbLayoutMenu_ToAddEdit.Controller = layoutMenu.Controller;
                            dbLayoutMenu_ToAddEdit.DefaultAction = layoutMenu.DefaultAction;
                            dbLayoutMenu_ToAddEdit.DisplayMenuToPublicIfPrivate = layoutMenu.DisplayMenuToPublicIfPrivate;
                            dbLayoutMenu_ToAddEdit.DisplayMenuBar = layoutMenu.DisplayMenuBar;
                            _dataContext.Save();
                            foreach (LayoutMenu_Translation dbLayoutMenu_Translation_ToAddEdit in dbLayoutMenu_ToAddEdit.LayoutMenu_Translation)
                            {
                                LayoutMenu_Translation_MetaModel layoutMenu_Translation = layoutMenu.Translations.Where(x => x.Id == dbLayoutMenu_Translation_ToAddEdit.Id).FirstOrDefault();
                                if (layoutMenu_Translation == null)
                                {
                                    throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.ErrMsg_LayoutMenuItemAddEdit_TranslationNotFound);
                                }
                                dbLanguage = _dataContext.Language_Rep.Query(x => x.Id == dbLayoutMenu_Translation_ToAddEdit.FK_Language).FirstOrDefault();
                                if (dbLanguage == null)
                                {
                                    throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, string.Format(Resources.ErrMsg_LayoutMenuItemEdit_UnknownLanguage, layoutMenu_Translation.Language.Language));
                                }
                                dbLayoutMenu_Translation_ToAddEdit.FK_LayoutMenu = dbLayoutMenu_ToAddEdit.Id;
                                dbLayoutMenu_Translation_ToAddEdit.FK_Language = dbLanguage.Id;
                                dbLayoutMenu_Translation_ToAddEdit.Active = layoutMenu_Translation.Active;
                                dbLayoutMenu_Translation_ToAddEdit.ButtonCaption = layoutMenu_Translation.ButtonCaption;
                                dbLayoutMenu_Translation_ToAddEdit.ButtonToolTip = layoutMenu_Translation.ButtonToolTip;
                                dbLayoutMenu_Translation_ToAddEdit.CssClass = layoutMenu_Translation.CssClass;
                                if (!(dbLayoutMenu_ToAddEdit.SortIndex == 1 && dbLayoutMenu_ToAddEdit.FK_LayoutMenu == null))
                                {
                                    dbLayoutMenu_Translation_ToAddEdit.MenuNameURLFormatted = layoutMenu_Translation.MenuNameURLFormatted;
                                }
                                _dataContext.Save();
                                Structure_Page dbStructure_Page = _dataContext.Structure_Page_Rep.Query(x => x.FK_LayoutMenu_Translation == dbLayoutMenu_Translation_ToAddEdit.Id && x.SortIndex == 1).FirstOrDefault();
                                if (dbStructure_Page == null)
                                {
                                    throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.ErrMsg_LayoutMenuItemEdit_StructurePageNotFound);
                                }
                                dbStructure_Page.Title = layoutMenu_Translation.PageTitle;
                                if (!(dbLayoutMenu_ToAddEdit.SortIndex == 1 && dbLayoutMenu_ToAddEdit.FK_LayoutMenu == null))
                                {
                                    dbStructure_Page.PageNameURLFormatted = layoutMenu_Translation.PageNameURLFormatted;
                                    dbStructure_Page.DirectURL = layoutMenu_Translation.DirectURL;
                                }
                                _dataContext.Save();
                            }
                        }
                        TS.Complete();
                    }
                    catch (INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException iex)
                    {
                        TS.Dispose();

                        toReturn.Data = new INNOVACALLAjaxResponse(
                            success: false,
                            domElementToUpdate: null,
                            htmlContent: null,
                            scriptToExecute: "$.fn.jqDialogAlert(a.messageTitle ,a.message,'');",
                            messageTitle: Resources.View_All_DialogErrorTitle,
                            message: iex.LayoutException(),
                            additionalData: null
                        );

                        return toReturn;
                    }
                    catch (Exception ex)
                    {
                        TS.Dispose();
                        INNOVACALL.Framework.Common.InnovacallExceptions.CommonException iex = new INNOVACALL.Framework.Common.InnovacallExceptions.CommonException(eMethod, eParameters, ex.GetFullException());
                        iex.LogIt();

                        toReturn.Data = new INNOVACALLAjaxResponse(
                            success: false,
                            domElementToUpdate: null,
                            htmlContent: null,
                            scriptToExecute: "$.fn.jqDialogAlert(a.messageTitle ,a.message,'');",
                            messageTitle: Resources.View_All_DialogErrorTitle,
                            message: iex.LayoutException(),
                            additionalData: null
                        );

                        return toReturn;
                    }
                }
                dbLanguage = _dataContext.Language_Rep.Query(x => x.Description == contentLanguage).FirstOrDefault();
                if (dbLanguage == null)
                {
                    throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, string.Format(Resources.ErrMsg_LayoutMenuItemFeed_UnknownLanguage, language));
                }
                newMenuBar = RenderMenuBar(_dataContext, dbLanguage, defaultLanguage, currentUser);

                toReturn.Data = new INNOVACALLAjaxResponse(
                    success: true,
                    domElementToUpdate: "#divMenuBar",
                    htmlContent: newMenuBar,
                    scriptToExecute: "$.fn.DocReady();",
                    messageTitle: null,
                    message: null,
                    additionalData: null
                );

            }
            return toReturn;
        }

        /// <summary>
        /// Remove a menu
        /// Warning, Removing a Menu remove also its translations
        /// </summary>
        /// <param name="language">The language.</param>
        /// <param name="jSonModel">The ajax model.</param>
        /// <returns>JsonResult.</returns>
        /// <exception cref="INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException">
        /// </exception>
        [HttpPost, Authorize(Roles = "Admin")]
        public JsonResult LayoutMenuItemRemoveItem(string language, LayoutMenuItemRemove_JSonModel jSonModel)
        {
            JsonResult toReturn = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            string eMethod = eMethodBase + "LayoutMenuItemRemoveItem[POST]";
            object eParameters = new { ajaxModel = jSonModel };
            string defaultLanguage = PortalEnvironment.DefaultLanguage;
            string contentLanguage = GetContentLanguage(jSonModel.DirectURL);
            MembershipUser currentUser = Membership.GetUser();
            LayoutMenu_Translation dbLayoutMenu_Translation;
            using (DataRepositories _dataContext = new DataRepositories())
            {
                Language dbLanguage = _dataContext.Language_Rep.Query(x => x.Description == contentLanguage).FirstOrDefault();
                if (dbLanguage == null)
                {
                    throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, string.Format(Resources.ErrMsg_LayoutMenuItemRemove_UnknownLanguage, language));
                }
                using (TransactionScope TS = new TransactionScope())
                {
                    try
                    {
                        if (jSonModel.LayoutMenuTranslationLayoutMenuParent == null)
                        {
                            dbLayoutMenu_Translation = _dataContext.LayoutMenu_Translation_Rep.Query(x => x.Id == jSonModel.LayoutMenu_Translation_Id && x.LayoutMenu.FK_LayoutMenu == null).FirstOrDefault();
                        }
                        else
                        {
                            dbLayoutMenu_Translation = _dataContext.LayoutMenu_Translation_Rep.Query(x => x.Id == jSonModel.LayoutMenu_Translation_Id && x.LayoutMenu.FK_LayoutMenu == jSonModel.LayoutMenuTranslationLayoutMenuParent).FirstOrDefault();
                        }
                        if (dbLayoutMenu_Translation == null)
                        {
                            INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException iex = new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.DynaStructure_MenuAction_MenuNotFound);
                            iex.LogIt();
                            throw iex;
                        }
                        LayoutMenu dbLayoutMenu = dbLayoutMenu_Translation.LayoutMenu;
                        //We check if parent LayoutMenu has child
                        if (dbLayoutMenu_Translation.LayoutMenu.LayoutMenu1.Count > 0)
                        {
                            toReturn.Data = new INNOVACALLAjaxResponse(
                                success: false,
                                domElementToUpdate: null,
                                htmlContent: null,
                                scriptToExecute: "$.fn.jqDialogAlert(a.messageTitle ,a.message,'');",
                                messageTitle: Resources.View_All_DialogErrorTitle,
                                message: Resources.DynaStructure_RemoveMenu_MenuHasChildren,
                                additionalData: null
                            );
                        }
                        else
                        {
                            IEnumerable<Language> dbLanguages = _dataContext.Language_Rep.GetAll().AsEnumerable();
                            foreach (var dbCurrentLanguage in dbLanguages)
                            {
                                if (dbCurrentLanguage == null) throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.Err_LanguageNotFound);
                                dbLayoutMenu_Translation = dbLayoutMenu.LayoutMenu_Translation.Where(x => x.FK_Language == dbCurrentLanguage.Id).FirstOrDefault();
                                if (dbLayoutMenu_Translation != null)
                                {
                                    List<int> Structure_PagesIdsToKill = _dataContext.Structure_Page_Rep.Query(x => x.FK_LayoutMenu_Translation == dbLayoutMenu_Translation.Id).Select(x => x.Id).ToList();
                                    foreach (int Structure_PagesIdToKill in Structure_PagesIdsToKill)
                                    {
                                        Structure_Page dbStructure_PageToKill = _dataContext.Structure_Page_Rep.GetById(Structure_PagesIdToKill);
                                        ManagedContent toRemove = dbStructure_PageToKill.ManagedContent.SingleOrDefault();
                                        if (toRemove != null)
                                        {
                                            _dataContext.ManagedContent_Rep.Remove(toRemove);
                                            _dataContext.Save();
                                            _dataContext.Structure_Page_Rep.Remove(dbStructure_PageToKill);
                                            _dataContext.Save();
                                        }
                                    }
                                    _dataContext.LayoutMenu_Translation_Rep.Remove(dbLayoutMenu_Translation);
                                    _dataContext.Save();
                                }
                            }
                            string layoutMenuNameToRemove = dbLayoutMenu.Name;
                            Nullable<int> removedParentId = dbLayoutMenu.FK_LayoutMenu;
                            int removedSortOrder = dbLayoutMenu.SortIndex;
                            _dataContext.LayoutMenu_Rep.Remove(dbLayoutMenu);
                            _dataContext.Save();
                            //LJO update sort orders
                            IEnumerable<int> layoutMenuIdToReorder;
                            if (removedParentId.HasValue)
                            {
                                layoutMenuIdToReorder = _dataContext.LayoutMenu_Rep.Query(x => x.FK_LayoutMenu == removedParentId && x.SortIndex >= removedSortOrder).OrderBy(x => x.SortIndex).Select(x => x.Id).AsEnumerable();
                            }
                            else
                            {
                                layoutMenuIdToReorder = _dataContext.LayoutMenu_Rep.Query(x => x.FK_LayoutMenu == null && x.SortIndex >= removedSortOrder).OrderBy(x => x.SortIndex).Select(x => x.Id).AsEnumerable();
                            }
                            int currentSI = removedSortOrder;
                            foreach (var id in layoutMenuIdToReorder)
                            {
                                var currentLM = _dataContext.LayoutMenu_Rep.Query(x => x.Id == id).FirstOrDefault();
                                currentLM.SortIndex = currentSI;
                                _dataContext.Save();
                                currentSI++;
                            }
                            Logger.Info(enLog.Business, string.Format("User [{0}] removed layout menu [{1}]", (currentUser == null ? "#Anonymous#" : currentUser.UserName), layoutMenuNameToRemove));
                        }
                        TS.Complete();
                    }
                    catch (INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException ex)
                    {
                        TS.Dispose();
                        toReturn.Data = new INNOVACALLAjaxResponse(
                            success: false,
                            domElementToUpdate: null,
                            htmlContent: null,
                            scriptToExecute: "$.fn.jqDialogAlert(a.messageTitle ,a.message,'');",
                            messageTitle: Resources.View_All_DialogErrorTitle,
                            message: Resources.DynaStructure_RemoveMenu_MenuHasChildren,
                            additionalData: null
                        );
                        return toReturn;
                    }
                    catch (Exception ex)
                    {
                        TS.Dispose();
                        INNOVACALL.Framework.Common.InnovacallExceptions.CommonException iex = new INNOVACALL.Framework.Common.InnovacallExceptions.CommonException(eMethod, eParameters, ex.Message);
                        iex.LogIt();
                        toReturn.Data = new INNOVACALLAjaxResponse(
                            success: false,
                            domElementToUpdate: null,
                            htmlContent: null,
                            scriptToExecute: "$.fn.jqDialogAlert(a.messageTitle ,a.message,'');",
                            messageTitle: Resources.View_All_DialogErrorTitle,
                            message: ex.LayoutException(),
                            additionalData: null
                        );
                        return toReturn;
                    }
                }
                string newMenuBar = RenderMenuBar(_dataContext, dbLanguage, defaultLanguage, currentUser);

                toReturn.Data = new INNOVACALLAjaxResponse(
                    success: true,
                    domElementToUpdate: "#divMenuBar",
                    htmlContent: newMenuBar,
                    scriptToExecute: "$.fn.DocReady();",
                    messageTitle: null,
                    message: null,
                    additionalData: null
                );


            }
            return toReturn;
        }

        /// <summary>
        /// Moves the menu element.
        /// </summary>
        /// <param name="language">The language.</param>
        /// <param name="jSonModel">The j son model.</param>
        /// <returns>JsonResult.</returns>
        /// <exception cref="INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException"></exception>
        [HttpPost, Authorize(Roles = "Admin")]
        public JsonResult LayoutMenuItemMove(string language, LayoutMenuItemMove_JSonModel jSonModel)
        {
            JsonResult toReturn = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            string eMethod = eMethodBase + "MoveMenuElement[POST]";
            object eParameters = new { jSonModel = jSonModel };
            string defaultLanguage = PortalEnvironment.DefaultLanguage;
            MembershipUser currentUser = Membership.GetUser();
            using (DataRepositories _dataContext = new DataRepositories())
            {
                string contentLanguage = GetContentLanguage(jSonModel.DirectURL);
                Language dbLanguage = _dataContext.Language_Rep.Query(x => x.Description == contentLanguage).FirstOrDefault();
                if (dbLanguage == null) throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.Err_LanguageNotFound);
                using (TransactionScope TS = new TransactionScope())
                {
                    try
                    {
                        LayoutMenu dbLayoutMenuToMove = _dataContext.LayoutMenu_Translation_Rep.Query(x => x.Id == jSonModel.LayoutMenu_Translation_Id).Select(x => x.LayoutMenu).SingleOrDefault();
                        LayoutMenu dbLayoutMenuToSwitch;
                        if (dbLayoutMenuToMove == null)
                        {
                            INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException iex = new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.DynaStructure_MenuAction_MenuNotFound);
                            iex.LogIt();
                            throw iex;
                        }
                        if (jSonModel.Direction == 1)
                        {
                            if (dbLayoutMenuToMove.FK_LayoutMenu == null)
                            {
                                dbLayoutMenuToSwitch = _dataContext.LayoutMenu_Rep.Query(x => x.FK_LayoutMenu == null && x.SortIndex > dbLayoutMenuToMove.SortIndex).OrderBy(x => x.SortIndex).FirstOrDefault();
                            }
                            else
                            {
                                dbLayoutMenuToSwitch = _dataContext.LayoutMenu_Rep.Query(x => x.FK_LayoutMenu == dbLayoutMenuToMove.FK_LayoutMenu && x.SortIndex > dbLayoutMenuToMove.SortIndex).OrderBy(x => x.SortIndex).FirstOrDefault();
                            }
                        }
                        else
                        {
                            if (dbLayoutMenuToMove.FK_LayoutMenu == null)
                            {
                                dbLayoutMenuToSwitch = _dataContext.LayoutMenu_Rep.Query(x => x.FK_LayoutMenu == null && x.SortIndex < dbLayoutMenuToMove.SortIndex).OrderByDescending(x => x.SortIndex).FirstOrDefault();
                            }
                            else
                            {
                                dbLayoutMenuToSwitch = _dataContext.LayoutMenu_Rep.Query(x => x.FK_LayoutMenu == dbLayoutMenuToMove.FK_LayoutMenu && x.SortIndex < dbLayoutMenuToMove.SortIndex).OrderByDescending(x => x.SortIndex).FirstOrDefault();
                            }
                        }
                        if (dbLayoutMenuToSwitch == null)
                        {
                            TS.Dispose();
                            INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException iex = new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, "dbLayoutMenuToSwitch was null");
                            iex.LogIt();
                            throw iex;
                        }
                        else
                        {
                            int currentSO = dbLayoutMenuToMove.SortIndex;
                            int newSO = currentSO + jSonModel.Direction;
                            dbLayoutMenuToSwitch.SortIndex = 9999;
                            _dataContext.Save();
                            dbLayoutMenuToMove.SortIndex = newSO;
                            _dataContext.Save();
                            dbLayoutMenuToSwitch.SortIndex = currentSO;
                            _dataContext.Save();
                            Logger.Info(enLog.Business, string.Format("User [{0}] moved layout menu [{1}]", (currentUser == null ? "#Anonymous#" : currentUser.UserName), dbLayoutMenuToMove.Name));
                            TS.Complete();
                        }
                    }
                    catch (INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException iex)
                    {
                        toReturn.Data = new INNOVACALLAjaxResponse(
                            success: false,
                            domElementToUpdate: null,
                            htmlContent: null,
                            scriptToExecute: "$.fn.jqDialogAlert(a.messageTitle ,a.message,'');",
                            messageTitle: Resources.View_All_DialogErrorTitle,
                            message: iex.LayoutException(),
                            additionalData: null
                        );

                        return toReturn;
                    }
                    catch (Exception ex)
                    {
                        TS.Dispose();
                        INNOVACALL.Framework.Common.InnovacallExceptions.CommonException iex = new INNOVACALL.Framework.Common.InnovacallExceptions.CommonException(eMethod, eParameters, ex.Message);
                        iex.LogIt();

                        toReturn.Data = new INNOVACALLAjaxResponse(
                            success: false,
                            domElementToUpdate: null,
                            htmlContent: null,
                            scriptToExecute: "$.fn.jqDialogAlert(a.messageTitle ,a.message,'');",
                            messageTitle: Resources.View_All_DialogErrorTitle,
                            message: iex.LayoutException(),
                            additionalData: null
                        );

                        return toReturn;
                    }
                }
                string newMenuBar = RenderMenuBar(_dataContext, dbLanguage, defaultLanguage, currentUser);

                toReturn.Data = new INNOVACALLAjaxResponse(
                    success: true,
                    domElementToUpdate: "#divMenuBar",
                    htmlContent: newMenuBar,
                    scriptToExecute: "$.fn.DocReady();",
                    messageTitle: null,
                    message: null,
                    additionalData: null
                );

            }
            return toReturn;
        }

        /// <summary>
        /// Toggles the activation.
        /// </summary>
        /// <param name="language">The language.</param>
        /// <param name="jSonModel">The j son model.</param>
        /// <returns>JsonResult.</returns>
        /// <exception cref="INNOVACALL.Framework.Common.InnovacallExceptions.HierarchyException"></exception>
        [HttpPost, Authorize(Roles = "Admin")]
        public JsonResult ToggleActivation(string language, LayoutMenuItemToggleActivation_JSonModel jSonModel)
        {
            JsonResult toReturn = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            string eMethod = eMethodBase + "ToggleActivation[POST]";
            object eParameters = new { jSonModel = jSonModel };
            string defaultLanguage = PortalEnvironment.DefaultLanguage;
            string contentLanguage = null;
            MembershipUser currentUser = Membership.GetUser();
            string newMenuBar = string.Empty;
            using (DataRepositories _dataContext = new DataRepositories())
            {
                try
                {
                    //uiLang <> contLang
                    contentLanguage = GetContentLanguage(jSonModel.DirectURL);
                    Language dbLanguage = _dataContext.Language_Rep.Query(x => x.Description == contentLanguage).FirstOrDefault();
                    LayoutMenu_Translation dbLayoutMenu_Translation = _dataContext.LayoutMenu_Translation_Rep.Query(x => x.Id == jSonModel.LayoutMenu_Translation_Id).SingleOrDefault();
                    if (dbLayoutMenu_Translation == null)
                    {
                        throw new INNOVACALL.Framework.Common.InnovacallExceptions.HierarchyException(eMethod, eParameters, Resources.DynaStructure_ToggleMenuActivation_NotAvailable);
                    }
                    dbLayoutMenu_Translation.Active = !dbLayoutMenu_Translation.Active;
                    _dataContext.Save();
                    Logger.Info(enLog.Business, string.Format("User [{0}] set layout menu [{1}] to [{2}]", (currentUser == null ? "#Anonymous#" : currentUser.UserName), dbLayoutMenu_Translation.LayoutMenu.Name, (dbLayoutMenu_Translation.Active ? "Active" : "Desactivated")));
                    newMenuBar = RenderMenuBar(_dataContext, dbLanguage, defaultLanguage, currentUser);
                }
                catch (Exception ex)
                {
                    INNOVACALL.Framework.Common.InnovacallExceptions.CommonException iex = new INNOVACALL.Framework.Common.InnovacallExceptions.CommonException(eMethod, eParameters, ex.Message);
                    iex.LogIt();
                    toReturn.Data = new INNOVACALLAjaxResponse(
                        success: false,
                        domElementToUpdate: null,
                        htmlContent: null,
                        scriptToExecute: "$.fn.jqDialogAlert(a.messageTitle ,a.message,'');",
                        messageTitle: Resources.View_All_DialogErrorTitle,
                        message: iex.LayoutException(),
                        additionalData: null
                        );
                    return toReturn;
                }

                toReturn.Data = new INNOVACALLAjaxResponse(
                    success: true,
                    domElementToUpdate: "#divMenuBar",
                    htmlContent: newMenuBar,
                    scriptToExecute: "$.fn.DocReady();",
                    messageTitle: null,
                    message: null,
                    additionalData: null
                );

                return toReturn;
            }
        }

        /// <summary>
        /// Renders the menu bar.
        /// </summary>
        /// <param name="_dataContext">The _data context.</param>
        /// <param name="dbLanguage">The db language.</param>
        /// <param name="defaultLanguage">The default language.</param>
        /// <returns>System.String.</returns>
        private string RenderMenuBar(DataRepositories _dataContext, Language dbLanguage, string defaultLanguage, MembershipUser currentUser)
        {
            string toReturn = string.Empty;
            LayoutMenuElements_MetaModel menuBarModel = new LayoutMenuElements_MetaModel();
            LayoutViewControllersStaticTools.FeedMenus(menuBarModel, _dataContext, dbLanguage, defaultLanguage, true, currentUser);
            toReturn = base.RenderPartialViewToString("_MenuBar", menuBarModel);
            return toReturn;
        }
        /// <summary>
        /// Determine new sort index for a menu
        /// </summary>
        /// <param name="_dataContext">The _data context.</param>
        /// <param name="applicationId">The application id.</param>
        /// <param name="fk_LayoutMenu">The FK_ layout menu.</param>
        /// <returns>System.Int32.</returns>
        private int NewSortIndex(DataRepositories _dataContext, Guid applicationId, Nullable<int> fk_LayoutMenu)
        {
            int toReturn = 1;
            if (fk_LayoutMenu != null)
            {
                toReturn = _dataContext.LayoutMenu_Rep.Query(x => x.FK_InnoApplication == applicationId && x.FK_LayoutMenu == fk_LayoutMenu).Count() + 1;
            }
            else
            {
                toReturn = _dataContext.LayoutMenu_Rep.Query(x => x.FK_InnoApplication == applicationId && x.FK_LayoutMenu == null).Count() + 1;
            }
            return toReturn;
        }

        /// <summary>
        /// Gets the content language from the direct url
        /// </summary>
        /// <param name="directURL">The direct URL.</param>
        /// <returns>System.String.</returns>
        private string GetContentLanguage(string directURL)
        {
            string toReturn = PortalEnvironment.DefaultLanguage;
            if (directURL.Length > 5)
            {
                toReturn = directURL.Substring(1, 5);
            }
            return toReturn;
        }
    }
}

